package com.jorado.etl.service;

import com.jorado.core.Result;
import com.jorado.etl.model.EtlInput;
import com.jorado.event.EventClient;
import com.jorado.search.core.service.impl.ExportToFileImpl;
import com.jorado.search.core.service.impl.SolrExporter;
import com.jorado.search.core.util.SolrUtils;
import com.jorado.search.solr.client.SolrjOption;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocument;
import org.springframework.context.annotation.Description;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

@Description("Solr 关键字语料抽取服务")
public final class SolrKeywordEtlService extends ExportToFileImpl<SolrDocument> {

    private int total;
    private int waitTime;
    private KeywordEtlService etlService;

    public SolrKeywordEtlService(SolrjOption positionSolr, String distFile) {
        this(positionSolr, distFile, true);
    }

    public SolrKeywordEtlService(SolrjOption positionSolr, String distFile, boolean deleteIfExists) {
        this(positionSolr, distFile, deleteIfExists, 0);
    }

    public SolrKeywordEtlService(SolrjOption positionSolr, String distFile, boolean deleteIfExists, int waitTime) {
        super(new SolrExporter(positionSolr, getSolrQuery()), distFile, deleteIfExists);
        this.waitTime = waitTime;
        this.etlService = new KeywordEtlService(this.distFile);
        this.setAfterFilter(this::after);
    }

    private static SolrQuery getSolrQuery() {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery("*:*");
        solrQuery.setFields("JOB_TITLE,JOB_DESC");
        solrQuery.setSort("STATE", SolrQuery.ORDER.asc);
        return solrQuery;
    }

    @Override
    protected void export(List<SolrDocument> dataList) {

        total += dataList.size();

        HashSet<EtlInput> etlList = new LinkedHashSet<>();

        String jobTitle;
        String jobDescription;

        for (SolrDocument doc : dataList) {

            jobTitle = SolrUtils.getDocValue(doc, "JOB_TITLE");
            jobDescription = SolrUtils.getDocValue(doc, "JOB_DESC");

            EtlInput etlInput = new EtlInput();

            etlInput.setJobTitle(jobTitle);
            etlInput.setJobDescription(jobDescription);

            etlList.add(etlInput);

        }

        this.etlService.save(etlList);

        try {
            Thread.sleep(waitTime);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    protected Result after(Result result) {

        EventClient.getDefault().asyncSubmitLog(String.format("共抽取职位:[%d]个", total));

        //TODO:对文件去重
        return Result.OK;
    }
}
